package com.app.service.impl;

/*
  @author 阿伟
  @create 2020-11-24:15:04
  逻辑层的复杂方法实现
*/

import com.app.condition.UserCondition;
import com.app.dao.UserDao;
import com.app.service.OrdersServer;
import com.app.service.OssService;
import com.app.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.entity.Code;
import com.common.entity.Orders;
import com.common.entity.ResponseResult;
import com.common.entity.User;
import com.common.utils.SMSUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    OrdersServer ordersServer;

    @Autowired
    OssService ossService;

    /**
     * 正则表达式：验证手机号
     */
    final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

    /*验证昵称*/
    final String REGEX_NICK = "^[A-Za-z0-9\u4e00-\u9fa5]+$";

    //分页查询
    @Override
    public void selectUserByLimit(Page<User> page, UserCondition userCondition) {

        //分页查询条件器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //判断是否有查询的条件
        if (ObjectUtils.isEmpty(userCondition)) {
            //没有条件则返回普通分页查询
            baseMapper.selectPage(page, queryWrapper);
            return;
        }

        //查询的条件
        String userPhone = userCondition.getUserPhone();
        String userNickname = userCondition.getUserNickname();
        String createTime = userCondition.getCreateTime();
        String modifyTime = userCondition.getModifyTime();
        //判断条件是否为空
        if (!StringUtils.isEmpty(userPhone)) {
            queryWrapper.like("user_phone", userPhone);
        }
        if (!StringUtils.isEmpty(userNickname)) {
            queryWrapper.like("user_nickname", userNickname);
        }
        if (!StringUtils.isEmpty(createTime)) {
            queryWrapper.like("user_createdate", createTime);
        }
        if (!StringUtils.isEmpty(modifyTime)) {
            queryWrapper.like("user_updatedate", modifyTime);
        }
        //分页和查询条件
        baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public ResponseResult sendSMS(String phone) {
        //验证
        if (Pattern.matches(REGEX_MOBILE, phone)) {
            //验证码
            String code = new SMSUitl().SendServer(phone);
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            //将手机号存入redis及设置过期时间
            opsForValue.set(phone, code, 60, TimeUnit.SECONDS);
            String SMSCode = opsForValue.get(phone);
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("ok", SMSCode);
        } else {
            return ResponseResult.error(Code.PARAM_ERROR).Data("msg", "请输入正确的手机号");
        }
    }

    @Override
    public ResponseResult userRegister(String phone, String nickname, String password,String yzm) {
        //验证
        if (!Pattern.matches(REGEX_MOBILE, phone)) {
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg", "请输入正确的手机号");
        }
        //判断redis中是否存在验证码
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String code = opsForValue.get(phone);
        if(!code.matches(yzm)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","验证码不存在");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone", phone);
        User olduser = userDao.selectOne(queryWrapper);
        Integer flag = 0;
        if (olduser != null) {
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg", "数据库中已经存在该用户名");
        } else {
            //新建用户对象
            User user = new User();
            user.setUserId(null);
            user.setUserPhone(phone);
            user.setUserPassword(password);
            user.setUserHeadshot(null);
            user.setUserNickname(nickname);
            user.setUserLogicflage(0);
            user.setUserVersion(1);
            user.setUserCreatedate(null);
            user.setUserUpdatedate(null);
            flag = userDao.insert(user);
        }
        //判断是否插入成功
        if (flag != 0) {
            return ResponseResult.success(Code.REGISTE_SUCCESS);
        }
        return ResponseResult.error(Code.REGISTER_ERROR);
    }

    @Override
    public ResponseResult getOrderByPhone(String phone) {
        //验证
        if (!Pattern.matches(REGEX_MOBILE, phone)) {
            return ResponseResult.error(Code.REQUEST_ERROR).Data("error", "请输入正确的手机号码");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone", phone);
        User user = userDao.selectOne(queryWrapper);
        String id = user.getUserId();
        List<Orders> ordersList = ordersServer.selectOrderByUserId(id);
        return ResponseResult.success(Code.REQUEST_SUCCESS).Data("orders", ordersList);
    }

    @Override
    public String getUserId(String phone) {
        //验证
        if (!Pattern.matches(REGEX_MOBILE, phone)) {
            return null;
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone", phone);
        User user = userDao.selectOne(queryWrapper);
        String id = user.getUserId();
        return id;
    }

    @Override
    public User getUserById(String id) {
        User user = baseMapper.selectById(id);
        return user;
    }

    @Override
    public ResponseResult modifyPass(String userPhone, String newpass, String yzm) {
        QueryWrapper userWrapper = new QueryWrapper();
        userWrapper.eq("user_phone",userPhone);
        User one = userDao.selectOne(userWrapper);
        if(one == null){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("error","账号不存在，请输入正确的账号");
        }
        //获取redis里面的验证码
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String code = opsForValue.get(userPhone);
        if(!code.matches(yzm)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("error","验证码错误或不存在");
        }
        User user = new User();

        user.setUserPassword(newpass);
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone",userPhone);  //条件
        //执行数据库更新方法
        int i = userDao.update(user, queryWrapper);
        return ResponseResult.success(Code.REQUEST_SUCCESS).Data("flag",i);
    }

    @Override
    public ResponseResult modifyNickname(String nickname,String phone) {
        //验证昵称是否合法
        if(!Pattern.matches(REGEX_NICK,nickname)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("error", "请输入正确的手机号码");
        }
        //判断修改是否合法
        if(StringUtils.isEmpty(phone)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","非法修改");
        }else {
            //查询数据库中是否存在该用户昵称
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_nickname",nickname);
            List users = userDao.selectList(queryWrapper);
            if(users.size() != 0){
                return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","数据库中已存在相同的昵称，请你换一个试试");
            }else{
                //执行修改操作
                User user = new User();
                user.setUserNickname(nickname);
                QueryWrapper userqw = new QueryWrapper();
                userqw.eq("user_phone",phone);
                int update = userDao.update(user, userqw);
                if(update == 1){
                    return ResponseResult.success(Code.REQUEST_SUCCESS).Data("msg","修改成功,您的新昵称为:"+nickname);
                }
                return ResponseResult.error(Code.UNKNOWN_ERROR);
            }
        }
    }

    @Override
    public ResponseResult getHeadByPhone(String phone) {
        //验证
        if(!Pattern.matches(REGEX_MOBILE,phone)){
            return ResponseResult.success(Code.REQUEST_ERROR).Data("error","请输入正确的手机号码");
        }
        //构造条件
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone",phone);
        User user = userDao.selectOne(queryWrapper);
        String headUrl = user.getUserHeadshot();
        if(StringUtils.isEmpty(headUrl)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","数据库中没有该用户，建议先注册");
        }else{
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("url",headUrl);
        }
    }

    @Override
    public ResponseResult getNickByPhone(String phone) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone",phone);
        User user = userDao.selectOne(queryWrapper);
        String nickname = user.getUserNickname();
        if(!StringUtils.isEmpty(nickname)){
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("nickname",nickname);
        }
        return ResponseResult.error(Code.REQUEST_ERROR);
    }

    @Override
    public ResponseResult upload(MultipartFile multipartFile, String phone) {
        //验证
        if(!Pattern.matches(REGEX_MOBILE,phone)){
            return ResponseResult.success(Code.REQUEST_ERROR).Data("error","请输入正确的手机号码");
        }
        //参数判空
        if(StringUtils.isEmpty(multipartFile) || StringUtils.isEmpty(phone)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","请传递正确的参数");
        }
        String url = ossService.uploadAliyun(multipartFile);
        User user = new User();
        user.setUserHeadshot(url);
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone",phone);
        //执行数据库更新方法
        int update = userDao.update(user, queryWrapper);
        if(update == 1){
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("url",url);
        }
        return ResponseResult.error(Code.REQUEST_ERROR).Data("msg",null);
    }

    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //参数判空
        if(StringUtils.isEmpty(multipartFile)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","请传递正确的参数");
        }
        String url = ossService.uploadAliyun(multipartFile);
        if(StringUtils.isEmpty(url)){
            return ResponseResult.error(Code.REQUEST_ERROR).Data("msg","请重试");
        }
        return ResponseResult.success(Code.REQUEST_SUCCESS).Data("url",url);
    }

}
